package com.fashion.web.filter;

import com.fashion.service.ColumnService;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * User: gnyk
 * Date: 13-3-14
 * Time: 下午11:10
 */
public class RequestFilter implements Filter {
    private ColumnService columnService;
    private static final Logger logger = Logger.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Get spring context and then get column service
        ServletContext servletContext = filterConfig.getServletContext();
        ApplicationContext context =
                WebApplicationContextUtils.getWebApplicationContext(servletContext);
        columnService = (ColumnService)
                context.getBean("columnService");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String topColumnUrl = request.getParameter("topColumnUrl");
        String columnUrl = request.getParameter("columnUrl");

        if (columnUrl.contains("_")) {
            columnUrl = columnUrl.split("_")[0];
        }

        if(columnUrl.endsWith("/")) {
            columnUrl = columnUrl.substring(0, columnUrl.length() - 1);
        }

        if (!columnService.isValidUrl(topColumnUrl, columnUrl)) {
            httpServletRequest.getRequestDispatcher("/management/error.action").forward(
                    request, response);

        }else{
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
